<template>
  <el-dialog :visible.sync="modals" title="发送货" class="order_box" :before-close="handleClose" width="750px">
    <el-form ref="formItem" :model="formItem" label-width="110px" @submit.native.prevent :rules="rules">
      <!-- 微信发货信息管理状态显示 -->
      <el-card v-if="wechatShippingEnabled" shadow="never" style="margin-bottom: 20px;">
        <div slot="header" class="clearfix">
          <span>微信发货信息管理</span>
          <el-tooltip content="微信小程序发货信息管理功能已启用" placement="top">
            <i class="el-icon-info" style="margin-left: 10px; color: #409EFF;"></i>
          </el-tooltip>
        </div>
        <div class="wechat-shipping-info">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">启用状态：</span>
                <el-tag :type="wechatShippingEnabled ? 'success' : 'info'" size="small">
                  {{ wechatShippingEnabled ? '已启用' : '未启用' }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">自动上传：</span>
                <el-tag :type="wechatConfig.autoUpload ? 'success' : 'warning'" size="small">
                  {{ wechatConfig.autoUpload ? '是' : '否' }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <el-button type="text" size="small" @click="openWechatConfig">配置管理</el-button>
                <el-button type="text" size="small" @click="queryWechatStatus">查询状态</el-button>
              </div>
            </el-col>
          </el-row>
          <el-row v-if="wechatShippingStatus" style="margin-top: 10px;">
            <el-col :span="24">
              <div class="shipping-status">
                <span class="label">发货状态：</span>
                <el-tag :type="getStatusType(wechatShippingStatus.status)" size="small">
                  {{ getStatusText(wechatShippingStatus.status) }}
                </el-tag>
                <span style="margin-left: 10px; color: #666; font-size: 12px;">
                  上传时间：{{ formatTime(wechatShippingStatus.uploadTime) }}
                </span>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 原有的发货类型选择 -->
      <el-form-item label="选择类型：">
        <el-radio-group v-model="formItem.type" @change="changeRadioType(formItem.type)">
          <el-radio label="1">发货</el-radio>
          <el-radio label="2">送货</el-radio>
          <el-radio label="3">虚拟</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 微信发货选项 -->
      <el-form-item v-if="wechatShippingEnabled" label="微信发货：">
        <el-checkbox v-model="formItem.enableWechatShipping">
          同时上传到微信小程序发货信息管理
        </el-checkbox>
        <div style="color: #909399; font-size: 12px; margin-top: 5px;">
          勾选后将自动上传发货信息到微信小程序平台
        </div>
      </el-form-item>

      <!-- 原有的发货表单内容 -->
      <div v-if="formItem.type==='1'">
        <el-form-item label="发货类型：" prop="expressId">
          <el-radio-group v-model="formItem.expressRecordType" @change="changeRadio(formItem.expressRecordType)">
            <el-radio label="1">手动填写</el-radio>
            <el-radio label="2" v-if="checkPermi(['admin:order:sheet:info'])">电子面单打印</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="快递公司：" prop="expressCode">
          <el-select v-model="formItem.expressCode" filterable style="width:80%;"
                     @change="onChangeExport(formItem.expressCode)">
            <el-option v-for="(item,i) in express" :value="item.code" :key="i" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formItem.expressRecordType === '1'" label="快递单号：" prop="expressNumber">
          <el-input v-model="formItem.expressNumber" placeholder="请输入快递单号" style="width:80%;"></el-input>
        </el-form-item>
        <template v-if="formItem.expressRecordType === '2'">
          <el-form-item label="电子面单：" class="express_temp_id" prop="expressTempId">
            <div class="acea-row">
              <el-select v-model="formItem.expressTempId" placeholder="请选择电子面单"
                         :class="[formItem.expressTempId?'width9':'width8']" @change="onChangeImg">
                <el-option v-for="(item,i) in exportTempList" :value="item.temp_id" :key="i"
                           :label="item.title"></el-option>
              </el-select>
              <div v-if="formItem.expressTempId" style="position: relative;">
                <div class="tempImgList ml10">
                  <div class="demo-image__preview">
                    <el-image
                      style="width: 36px; height: 36px"
                      :src="tempImg"
                      :preview-src-list="[tempImg]"
                    />
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="寄件人姓名：" prop="toName">
            <el-input v-model="formItem.toName" placeholder="请输入寄件人姓名" style="width:80%;"></el-input>
          </el-form-item>
          <el-form-item label="寄件人电话：" prop="toTel">
            <el-input v-model="formItem.toTel" placeholder="请输入寄件人电话" style="width:80%;"></el-input>
          </el-form-item>
          <el-form-item label="寄件人地址：" prop="toAddr">
            <el-input v-model="formItem.toAddr" placeholder="请输入寄件人地址" style="width:80%;"></el-input>
          </el-form-item>
        </template>
      </div>
      <div v-if="formItem.type==='2'">
        <el-form-item label="送货人姓名：" prop="deliveryName">
          <el-input v-model="formItem.deliveryName" placeholder="请输入送货人姓名" style="width:80%;"></el-input>
        </el-form-item>
        <el-form-item label="送货人电话：" prop="deliveryTel">
          <el-input v-model="formItem.deliveryTel" placeholder="请输入送货人电话" style="width:80%;"></el-input>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="" >
          <div style="color:#CECECE;">顺丰请输入单号：收件人或寄件人手机号后四位</div>
          <div style="color:#CECECE;">例如：SF000000000000:3941</div>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer">
      <el-button type="primary" @click="putSend('formItem')" :loading="submitLoading">提交</el-button>
      <el-button @click="cancel('formItem')">取消</el-button>
      <el-button v-if="wechatShippingEnabled && orderId" type="info" @click="manualUploadWechat" :loading="uploadLoading">
        手动上传微信
      </el-button>
    </div>

    <!-- 微信发货配置弹窗 -->
    <wechat-shipping-config
      :visible.sync="configVisible"
      @refresh="loadWechatConfig"
    />
  </el-dialog>
</template>

<script>
  import { orderSendApi, orderSendWithWechatApi, uploadWechatShippingApi, sheetInfoApi } from '@/api/order'
  import { expressAllApi, exportTempApi } from '@/api/sms'
  import { 
    getWechatShippingConfigApi, 
    isWechatShippingEnabledApi,
    getWechatShippingStatusApi,
    retryUploadShippingApi
  } from '@/api/wechatShipping'
  import { checkPermi } from "@/utils/permission";
  import { Debounce } from '@/utils/validate'
  import WechatShippingConfig from './components/WechatShippingConfig'

  const validatePhone = (rule, value, callback) => {
    if (!value) {
      return callback(new Error('请填写手机号'));
    } else if (!/^1[3456789]\d{9}$/.test(value)) {
      callback(new Error('手机号格式不正确!'));
    } else {
      callback();
    }
  };

  export default {
    name: 'orderSend',
    components: {
      WechatShippingConfig
    },
    props: {
      orderId: String
    },
    data() {
      return {
        formItem: {
          type: '1',
          expressRecordType: '1',
          expressId: '',
          expressCode: '',
          deliveryName: '',
          deliveryTel: '',
          expressNumber: '',
          expressTempId: '',
          toAddr: '',
          toName: '',
          toTel: '',
          orderNo: '',
          enableWechatShipping: true // 默认启用微信发货
        },
        modals: false,
        express: [],
        exportTempList: [],
        tempImg: '',
        rules: {
          toName: [
            {required: true, message: '请输寄件人姓名', trigger: 'blur'}
          ],
          toTel: [
            {required: true, validator: validatePhone, trigger: 'blur'}
          ],
          toAddr: [
            {required: true, message: '请输入寄件人地址', trigger: 'blur'}
          ],
          expressCode: [
            {required: true, message: '请选择快递公司', trigger: 'change'}
          ],
          expressNumber: [
            {required: true, message: '请输入快递单号', trigger: 'blur'}
          ],
          expressTempId: [
            {required: true, message: '请选择电子面单', trigger: 'change'}
          ],
          deliveryName: [
            {required: true, message: '请输入送货人姓名', trigger: 'blur'}
          ],
          deliveryTel: [
            {required: true, validator: validatePhone, trigger: 'blur'}
          ]
        },
        expressType: 'normal',
        // 微信发货相关
        wechatShippingEnabled: false,
        wechatConfig: {
          enabled: false,
          autoUpload: true,
          specialMode: 1,
          retryTimes: 3,
          retryInterval: 30
        },
        wechatShippingStatus: null,
        configVisible: false,
        submitLoading: false,
        uploadLoading: false
      }
    },
    mounted() {
      this.initWechatShipping()
    },
    methods: {
      checkPermi,
      
      // 初始化微信发货功能
      async initWechatShipping() {
        try {
          // 检查微信发货功能是否启用
          const enabledRes = await isWechatShippingEnabledApi()
          this.wechatShippingEnabled = enabledRes.data
          
          if (this.wechatShippingEnabled) {
            // 加载微信发货配置
            await this.loadWechatConfig()
            
            // 如果是编辑模式（有订单ID），查询发货状态
            if (this.orderId) {
              await this.loadWechatShippingStatus()
            }
          }
        } catch (error) {
          console.error('初始化微信发货功能失败:', error)
        }
      },

      // 加载微信发货配置
      async loadWechatConfig() {
        try {
          const res = await getWechatShippingConfigApi()
          this.wechatConfig = res.data
          this.formItem.enableWechatShipping = res.data.autoUpload
        } catch (error) {
          console.error('加载微信发货配置失败:', error)
        }
      },

      // 加载微信发货状态
      async loadWechatShippingStatus() {
        if (!this.orderId) return
        
        try {
          const res = await getWechatShippingStatusApi({ orderKey: this.orderId })
          if (res.data && res.data.errCode === 0) {
            this.wechatShippingStatus = res.data
          }
        } catch (error) {
          console.error('查询微信发货状态失败:', error)
        }
      },

      // 查询微信发货状态
      async queryWechatStatus() {
        if (!this.orderId) {
          this.$message.warning('请先选择订单')
          return
        }
        
        this.loadWechatShippingStatus()
        this.$message.success('状态查询完成')
      },

      // 打开微信发货配置
      openWechatConfig() {
        this.configVisible = true
      },

      // 手动上传微信发货信息
      async manualUploadWechat() {
        if (!this.orderId) {
          this.$message.warning('请先选择订单')
          return
        }

        this.uploadLoading = true
        try {
          const res = await uploadWechatShippingApi({ orderNo: this.orderId })
          if (res.code === 200) {
            this.$message.success('微信发货信息上传成功')
            await this.loadWechatShippingStatus()
          } else {
            this.$message.error(res.message || '上传失败')
          }
        } catch (error) {
          this.$message.error('上传失败: ' + error.message)
        } finally {
          this.uploadLoading = false
        }
      },

      // 获取发货状态样式
      getStatusType(status) {
        const statusMap = {
          0: 'info',    // 未发货
          1: 'success', // 已发货
          2: 'success', // 已收货
          3: 'warning', // 退款中
          4: 'danger',  // 已退款
          5: 'danger'   // 退款失败
        }
        return statusMap[status] || 'info'
      },

      // 获取发货状态文本
      getStatusText(status) {
        const statusMap = {
          0: '未发货',
          1: '已发货',
          2: '已收货',
          3: '退款中',
          4: '已退款',
          5: '退款失败'
        }
        return statusMap[status] || '未知'
      },

      // 格式化时间
      formatTime(timestamp) {
        if (!timestamp) return '--'
        return new Date(timestamp).toLocaleString()
      },

      // 默认信息
      sheetInfo() {
        sheetInfoApi().then(async res => {
          this.formItem.toAddr = res.exportToAddress || '';
          this.formItem.toName = res.exportToName || '';
          this.formItem.toTel = res.exportToTel || '';
        })
      },
      
      // 快递公司选择
      onChangeExport(val) {
        this.formItem.expressTempId = '';
        if (this.formItem.expressRecordType === '2') this.exportTemp(val);
      },
      
      // 电子面单模板
      exportTemp(val) {
        exportTempApi({com: val}).then(async res => {
          this.exportTempList = res.data.data || [];
        })
      },
      
      onChangeImg(item) {
        this.exportTempList.map(i => {
          if (i.temp_id === item) this.tempImg = i.pic
        })
      },
      
      changeRadioType() {
        this.formItem.expressId = ''
        this.formItem.expressCode = ''
      },
      
      changeRadio(o) {
        if (o == 2){
          this.expressType = 'elec'
        }else{
          this.expressType = 'normal'
        }
        this.formItem.expressId = ''
        this.formItem.expressCode = ''
        this.getList();
      },
      
      // 物流公司列表
      getList() {
        expressAllApi({type: this.expressType}).then(async res => {
          this.express = res
        })
      },
      
      // 提交发货（修改为支持微信发货）
      putSend: Debounce(function(name) {
        this.formItem.orderNo = this.orderId;
        this.$refs[name].validate(async (valid) => {
          if (valid) {
            this.submitLoading = true
            try {
              // 根据是否启用微信发货选择不同的API
              const apiMethod = this.wechatShippingEnabled && this.formItem.enableWechatShipping 
                ? orderSendWithWechatApi 
                : orderSendApi

              await apiMethod(this.formItem)
              
              this.$message.success('发送货成功');
              
              // 如果启用了微信发货，显示相关信息
              if (this.wechatShippingEnabled && this.formItem.enableWechatShipping) {
                this.$message.info('发货信息已同步上传到微信小程序', { duration: 3000 });
                // 延迟查询微信发货状态
                setTimeout(() => {
                  this.loadWechatShippingStatus()
                }, 2000)
              }
              
              this.modals = false;
              this.$refs[name].resetFields();
              this.$emit('submitFail')
            } catch (error) {
              this.$message.error('发货失败: ' + (error.message || '未知错误'))
            } finally {
              this.submitLoading = false
            }
          } else {
            this.$message.error('请填写信息');
          }
        })
      }),
      
      handleClose() {
        this.cancel('formItem');
      },
      
      cancel(name) {
        this.modals = false;
        this.$refs[name].resetFields();
        this.formItem.type = '1';
        this.formItem.expressRecordType = '1';
        this.formItem.enableWechatShipping = this.wechatConfig.autoUpload;
        this.wechatShippingStatus = null;
      }
    }
  }
</script>

<style scoped lang="scss">
  .width8 {
    width: 80%;
  }

  .width9 {
    width: 70%;
  }

  .tempImgList {
    width: 38px !important;
    height: 30px !important;
    cursor: pointer;
    position: absolute;
    z-index: 11;
    img {
      width: 38px !important;
      height: 30px !important;
    }
  }

  .wechat-shipping-info {
    .info-item {
      margin-bottom: 10px;
      .label {
        font-weight: 500;
        color: #606266;
      }
    }
    
    .shipping-status {
      padding: 10px;
      background-color: #f5f7fa;
      border-radius: 4px;
      .label {
        font-weight: 500;
        color: #606266;
      }
    }
  }

  ::v-deep .el-card__header {
    padding: 10px 20px;
    border-bottom: 1px solid #ebeef5;
    font-size: 14px;
    font-weight: 500;
  }

  ::v-deep .el-card__body {
    padding: 15px 20px;
  }
</style>
